<template>
    <div class="avatar-container">
        <div v-if="imageUrl" class="avatar-preview">
            <img :src="imageUrl" alt="用户头像" class="avatar-img">
        </div>
        <div v-else class="avatar-placeholder">
            <i class="el-icon-user"></i>
            <p>点击上传图片</p>
        </div>
    </div>
    <el-upload class="avatar-uploader" :disabled="!qiniuToken" :action="qiniuUploadUrl" :data="{ token: qiniuToken }"
        :on-success="handleUploadSuccess" :before-upload="beforeUpload">
        <template #default>
            <button v-if="!qiniuToken" class="el-button el-button--primary">获取 Token 中...</button>
            <button v-else class="el-button el-button--primary">点击上传图片</button>
        </template>
    </el-upload>
</template>

<script lang="ts" setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import request from '@/request'
//七牛云配置
const qiniuToken = ref('')
const qiniuUploadUrl = 'https://up-z2.qiniup.com';
const qiniuDomain = ref('http://sxdk8tktw.hn-bkt.clouddn.com')//七牛云存储空间域名
const imageUrl =ref('')
//请求头
onMounted(() => {
    fetchQiniuToken()
})
const fetchQiniuToken = async () => {
    const loginToken = localStorage.getItem('token')
    request({
        url: '/picture/',
        method: 'get',
        headers: {
            Authorization: `Bearer ${loginToken}`
        }
    }).then(response => {
        if (response.status == 200) {
            qiniuToken.value = response.data.token.trim();
            ElMessage.success('获取token成功')
            console.log(response.data)// 新增日志
        }
    }).catch(error => {
        ElMessage.error('获取上传的token失败' + error.message)
    })
}
//上传token成功后的回调
const handleUploadSuccess = async (response) => {
    console.log("七牛云响应:", response); // 新增日志，确认是否有key
    if (response.key) {
        const url = `${qiniuDomain.value}/${response.key}`;
        // 可选：将URL保存到后端（需携带登录Token）
        await updateUserAvatar(url)
    } else {
        ElMessage.error('上传失败：' + response.error);
    }
}

//上传前校验
const beforeUpload = (file) => {
    const isImage = file.type.startsWith('image/')
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isImage) {
        ElMessage.error('请选择图片文件(支持JPG/PNG/GIF等格式)')
        return false
    }
    if (!isLt2M) {
        ElMessage.error('图片大小不能超过2MB')
        return false
    }
    return true
}
//修改头像
const updateUserAvatar = async (url) => {
    const localToken = localStorage.getItem('token')
    await request({
        url: '/account/',
        method: 'put',
        data: { avatar: url },
        headers: {
            Authorization: `Bearer ${localToken}`
        }
    }).then(response => {
        ElMessage.success('头像更新成功')
        imageUrl.value = url;
        console.log('头像链接', imageUrl.value)
    }).catch(error => {
        ElMessage.error('头像更新失败' + error.message)
    })
}

</script>

<style scoped>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
.avatar-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
}

.avatar-preview {
  width: 150px;  /* 头像尺寸，可调整 */
  height: 150px;
  border-radius: 50%;  /* 圆形头像 */
  overflow: hidden;    /* 裁剪超出部分 */
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.avatar-img {
  width: 100%;
  height: 100%;
  object-fit: cover;  /* 保持比例填充 */
}

.avatar-placeholder {
  width: 150px;
  height: 150px;
  border: 2px dashed #e0e0e0;
  border-radius: 50%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #999;
  cursor: pointer;
}

.avatar-placeholder i {
  font-size: 48px;
  margin-bottom: 8px;
}
</style>